#include "threadPool.h"

int initDirStack(dirStack_t *dirstack, int root_dir_id) {
  dirNode_t *bottom = (dirNode_t *)calloc(1, sizeof(dirNode_t));
  bottom->data = root_dir_id;
  dirstack->bottom = bottom;
  dirstack->top = bottom;
  dirstack->size = 0;
  printf("root: \"%d\"\n", dirstack->bottom->data);
  return 0;
}

int pushDirStack(dirStack_t *dirstack, int data) {
  dirNode_t *push = (dirNode_t *)calloc(1, sizeof(dirNode_t));
  push->data = data;
  dirstack->top->pnext = push;
  dirstack->top = push;
  ++dirstack->size;
  printf("pushed \"%d\"\n", dirstack->top->data);
  return 0;
}

int popDirStack(dirStack_t *dirstack) {
  if (dirstack->size != 0) {
    dirNode_t *cur = dirstack->bottom;
    while (cur->pnext != dirstack->top) {
      cur = cur->pnext;
    }
    printf("poped \"%d\"\n", dirstack->top->data);
    free(dirstack->top);
    cur->pnext = NULL;
    dirstack->top = cur;
    --dirstack->size;
  } else {
    printf("nothing to pop now!\n");
  }
  return 0;
}

int cleanDirStack(dirStack_t *dirstack) {
  while (dirstack->size != 0) {
    popDirStack(dirstack);
  }
  printf("dirStack cleaned!\n");
  return 0;
}

int destroyDirStack(dirStack_t *dirstack) {
  if (dirstack->size != 0) {
    cleanDirStack(dirstack);
  }
  free(dirstack->bottom);
  dirstack->bottom = NULL;
  dirstack->top = NULL;
  printf("dirStack destroyed!\n");
  return 0;
}

int copyDirStack(dirStack_t *copy, dirStack_t *paste) {
  cleanDirStack(paste);
  dirNode_t *cur = copy->bottom->pnext;
  for (int i = 0; i < copy->size; ++i) {
    pushDirStack(paste, cur->data);
    cur = cur->pnext;
  }
  return 0;
}

int printDirStack(dirStack_t *dirstack) {
  dirNode_t *cur = dirstack->bottom;
  while (cur != NULL) {
    printf("%d", cur->data);
    if (cur->pnext != NULL) {
      printf(" -> ");
    } else {
      printf("\n");
    }
    cur = cur->pnext;
  }
  return 0;
}
